<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="listQuery.gender" placeholder="请选择" clearable>
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="入校时间">
          <el-date-picker
            v-model="listQuery.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleCreate">新增学生</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      border
    >
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="gender" label="性别" width="80" />
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="joinDate" label="入校时间" width="120" />
      <el-table-column prop="phone" label="联系电话" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status === '1' ? 'success' : 'info'">
            {{ row.status === '1' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="temp.gender" placeholder="请选择">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="temp.age" :min="1" :max="120" />
        </el-form-item>
        <el-form-item label="入校时间" prop="joinDate">
          <el-date-picker
            v-model="temp.joinDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="temp.status">
            <el-radio label="1">正常</el-radio>
            <el-radio label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'

export default {
  name: 'PartyMemberList',
  components: { Pagination },
  data() {
    return {
      // 模拟的数据库数据
      mockData: [
        {
          id: 1,
          name: '张三',
          gender: '男',
          age: 30,
          joinDate: '2020-01-01',
          phone: '13800138000',
          status: '1'
        },
        {
          id: 2,
          name: '李四',
          gender: '女',
          age: 28,
          joinDate: '2021-06-15',
          phone: '13900139000',
          status: '1'
        },
        {
          id: 3,
          name: '王五',
          gender: '男',
          age: 35,
          joinDate: '2019-03-20',
          phone: '13700137000',
          status: '2'
        }
      ],
      list: [], // 当前显示的列表数据
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        gender: undefined,
        dateRange: []
      },
      temp: {
        id: undefined,
        name: '',
        gender: '',
        age: 25,
        joinDate: '',
        phone: '',
        status: '1'
      },
      dialogVisible: false,
      dialogTitle: '',
      dialogType: '',
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        joinDate: [{ required: true, message: '请选择入校时间', trigger: 'change' }],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      this.listLoading = true
      setTimeout(() => {
        // 1. 根据查询条件过滤数据
        let result = [...this.mockData]
        
        const { name, gender, dateRange } = this.listQuery
        
        if (name) {
          result = result.filter(item => item.name.includes(name))
        }
        
        if (gender) {
          result = result.filter(item => item.gender === gender)
        }
        
        if (dateRange && dateRange.length === 2) {
          const [startDate, endDate] = dateRange
          result = result.filter(item => {
            const joinDate = new Date(item.joinDate)
            return joinDate >= new Date(startDate) && joinDate <= new Date(endDate)
          })
        }

        // 2. 更新总数
        this.total = result.length
        
        // 3. 分页处理
        const { page, limit } = this.listQuery
        const start = (page - 1) * limit
        const end = page * limit
        
        // 4. 设置当前页数据
        this.list = result.slice(start, end)
        
        this.listLoading = false
      }, 500)
    },
    
    // 查询
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    
    // 重置查询
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        gender: undefined,
        dateRange: []
      }
      this.getList()
    },
    
    // 新增
    handleCreate() {
      this.dialogType = 'create'
      this.dialogTitle = '新增学生'
      this.temp = {
        id: undefined,
        name: '',
        gender: '',
        age: 25,
        joinDate: '',
        phone: '',
        status: '1'
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    // 编辑
    handleUpdate(row) {
      this.dialogType = 'update'
      this.dialogTitle = '编辑学生'
      this.temp = Object.assign({}, row)
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该学生信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.mockData.findIndex(item => item.id === row.id)
        this.mockData.splice(index, 1)
        this.$message.success('删除成功')
        this.getList()
      })
    },
    
    // 保存数据
    saveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.dialogType === 'create') {
            // 新增：生成新的ID并添加到模拟数据中
            const newId = Math.max(...this.mockData.map(item => item.id)) + 1
            this.temp.id = newId
            this.mockData.push(Object.assign({}, this.temp))
          } else {
            // 编辑：更新模拟数据中的对应记录
            const index = this.mockData.findIndex(item => item.id === this.temp.id)
            this.mockData.splice(index, 1, Object.assign({}, this.temp))
          }
          
          this.dialogVisible = false
          this.$message.success(this.dialogType === 'create' ? '新增成功' : '更新成功')
          this.getList()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
  
  .el-form-item {
    margin-bottom: 10px;
  }
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style> 